﻿using Demos.DesignPatterns._01_Singleton;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demos.DesignPatterns._06_策略模式
{
    /// <summary>
    /// 
    /// </summary>
    public class ShoppingCart
    {
        private readonly List<CartItem> _items = new List<CartItem>();

        private IDiscountStrategy _discountStrategy;

        public void SetDiscountStrategy(IDiscountStrategy discountStrategy)
        {
            _discountStrategy = discountStrategy;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="productId"></param>
        /// <param name="productName"></param>
        /// <param name="price"></param>
        /// <param name="quantity"></param>
        public void AddItem(int productId, string productName, decimal price, int quantity)
        {
            _items.Add(new CartItem
            {
                ProductId = productId,
                ProductName = productName,
                Price = price,
                Quantity = quantity
            });
        }

        /// <summary>
        /// 计算折扣
        /// </summary>
        /// <returns></returns>
        public decimal CalculateTotal()
        {
            decimal subtotal = 0;
            foreach (var item in _items)
            {
                subtotal += item.Price * item.Quantity;
            }

            // 应用折扣策略
            return _discountStrategy?.ApplyDiscount(subtotal) ?? subtotal;
        }

        /// <summary>
        /// 
        /// </summary>
        public void DisplayCart()
        {
            foreach (var item in _items)
            {
                Console.WriteLine($"购物车商品：{item.ProductName} x {item.Quantity} @ {item.Price:C} = {item.Price * item.Quantity:C}");
            }
            decimal total = 0;
            foreach (var item in _items)
            {
                total += item.Price * item.Quantity;
            }
            Console.WriteLine($"商品总价:{total}");
            if(_discountStrategy is not NoDiscount && _discountStrategy != null)
            {
                decimal total2 = _discountStrategy?.ApplyDiscount(total) ?? total;
                Console.WriteLine($"折扣后总计: {total2:C}");
            }
            else
            {
                Console.WriteLine($"无折扣，总计:{total:C}");
            }

        }
    }
}
